package com.cherry.androidcode.video

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cherry.androidcode.R
import com.cherry.androidcode.entity.MultiVideoDetail
import com.cherry.androidcode.image.GlideApp
import com.cherry.androidcode.mvp1.MVPActivity
import com.cherry.androidcode.recyclerView.AbsPinnedDataProvider
import com.cherry.androidcode.recyclerView.AbsPinnedHeaderListAdapter
import com.cherry.androidcode.recyclerView.AbsPinnedHeaderProvider
import com.cherry.androidcode.recyclerView.QuickViewHolder
import com.cherry.androidcode.util.StatusBarUtil
import com.cherry.androidcode.util.resToColor
import com.cherry.androidcode.util.setGone
import com.cherry.androidcode.util.setVisible
import com.oushangfeng.pinnedsectionitemdecoration.PinnedHeaderItemDecoration
import com.parkingwang.android.view.SwStateToast
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.Debuger
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import com.yanyusong.y_divideritemdecoration.Y_Divider
import com.yanyusong.y_divideritemdecoration.Y_DividerBuilder
import com.yanyusong.y_divideritemdecoration.Y_DividerItemDecoration
import kotlinx.android.synthetic.main.activity_video_play.*

/**
 * @author Cherry(dongmiansheng@gmail.com)
 * @since 2019/8/31
 */

class VideoPlayActivity : MVPActivity<VideoPlayContract.View, VideoPlayPresenter>(), VideoPlayContract.View {

    private var isPause = false
    private var isPlay = false

    private lateinit var recyclerViewLayoutManager: RecyclerView.LayoutManager

    override val activityLayoutRes = R.layout.activity_video_play


    private val adapter by lazy {
        object : AbsPinnedHeaderListAdapter<MultiVideoDetail, QuickViewHolder>(null) {
            //头部黏连有个bug，headerView的childView最好填充数据确认高度，否则黏连的高度会变小
            override fun pinnedHeaderProvider() = object : AbsPinnedHeaderProvider<MultiVideoDetail, QuickViewHolder>() {
                override val layoutId: Int = R.layout.item_pinned_header

                override fun convert(helper: BaseViewHolder, item: MultiVideoDetail) {
                    helper.setText(R.id.tv_header, item.source)
                }

            }

            override fun pinnedDataProvider() = object : AbsPinnedDataProvider<MultiVideoDetail, QuickViewHolder>(recyclerViewLayoutManager) {

                override val layoutId: Int = R.layout.item_test_card_view_simple


                override fun convert(helper: QuickViewHolder, data: MultiVideoDetail, position: Int) {
                    helper.setText(R.id.tv_title, data.videoList?.name)
                }

            }

            override fun isHeaderTypeCondition(t: MultiVideoDetail) = t.source != null && t.videoList == null

            override fun isDataTypeCondition(t: MultiVideoDetail) = t.source == null && t.videoList != null

        }
    }

    private val orientationHelper by lazy {
        OrientationUtils(this, detail_player)
    }

    private val gsyVideoOption by lazy {
        GSYVideoOptionBuilder()
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setSeekRatio(1f)
                .setCacheWithPlay(true)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setStatusBarColor(this, Color.TRANSPARENT)
        StatusBarUtil.addMarginTopEqualStatusBarHeight(toolbar)
//        setSupportActionBar(toolbar)
        //这里直接设置toolbar标题不起作用，需要把标题设置在collapsingToolbarLayout上
//        collapsingToolbarLayout.title = intent.getStringExtra("videoName")

        initRv()
        initData()

        GlideApp.with(this)
                .load(intent.getStringExtra("videoCover"))
                .placeholder(R.drawable.bar_status_alpha_bg)
                .fitCenter()
                .into(iv_cover)
        //初始化不打开外部的旋转
        orientationHelper.isEnable = false

        detail_player.fullscreenButton.setOnClickListener {
            //直接横屏
            orientationHelper.resolveByClick()

            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            detail_player.startWindowFullscreen(this, true, true)
        }

        fl_player_container.setOnClickListener {
            appbar.setExpanded(true, true)
        }

    }

    private fun initRv() {
        //重点设置：头部黏连的分组布局
        recyclerView.addItemDecoration(
                PinnedHeaderItemDecoration.Builder(AbsPinnedHeaderListAdapter.TYPE_HEADER)
                        //只对置顶的头部有效，界面出现的其他头部点击无效，当没有设置点击时，可以穿透点击事件
//                        .setClickIds(R.id.item_root)
//                        .setHeaderClickListener(object : OnHeaderClickListener {
//                            override fun onHeaderLongClick(view: View?, id: Int, position: Int) {
//                            }
//
//                            override fun onHeaderClick(view: View?, id: Int, position: Int) {
//                                SwToast.showShort(adapter.getItem(position)?.source)
//                            }
//                        })
                        .create())
        recyclerViewLayoutManager = GridLayoutManager(this, 2)
        recyclerView.layoutManager = recyclerViewLayoutManager
        recyclerView.adapter = adapter
        recyclerView.addItemDecoration(object : Y_DividerItemDecoration(this) {
            override fun getDivider(itemPosition: Int): Y_Divider {
                val isDataType = AbsPinnedHeaderListAdapter.TYPE_DATA == adapter.getItemViewType(itemPosition)
                return Y_DividerBuilder()
                        .setTopSideLine(isDataType, R.color.transparent.resToColor(), 5f, 0f, 0f)
                        .setLeftSideLine(isDataType, R.color.transparent.resToColor(), 5f, 0f, 0f)
                        .setRightSideLine(isDataType, R.color.transparent.resToColor(), 5f, 0f, 0f)
                        .setBottomSideLine(isDataType && (itemPosition == adapter.data.size - 1 || AbsPinnedHeaderListAdapter.TYPE_HEADER == adapter.getItemViewType(itemPosition + 1)),
                                R.color.transparent.resToColor(), 5f, 0f, 0f)
                        .create()
            }
        })
        adapter.setOnItemClickListener { _, _, position ->
            play(adapter.getItem(position)?.videoList?.url, adapter.getItem(position)?.videoList?.name)
        }
    }

    override fun onBackPressed() {
        orientationHelper.backToProtVideo()
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        super.onBackPressed()
    }


    override fun onPause() {
        getCurPlay().onVideoPause()
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        getCurPlay().onVideoResume()
        super.onResume()
        isPause = false
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isPlay) {
            getCurPlay().release()
        }
        orientationHelper.releaseListener()
    }


    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detail_player.onConfigurationChanged(this, newConfig, orientationHelper, true, true)
        }
    }


    private fun getCurPlay(): GSYVideoPlayer {
        return if (detail_player.fullWindowPlayer != null) {
            detail_player.fullWindowPlayer
        } else detail_player
    }

    @SuppressLint("CheckResult")
    private fun play(url: String?, name: String?) {
        if (url.isNullOrEmpty()) {
            SwStateToast.failed().show("视频播放地址不存在")
            return
        }
        gsyVideoOption.setVideoTitle(name)
        mvpPresenter?.loadVideoUrl(url)

    }

    @SuppressLint("CheckResult")
    private fun initData() {
        val videoLink = intent.getStringExtra("videoLink")
        if (videoLink.isNullOrEmpty()) {
            SwStateToast.tip().show("视频链接不存在")
            return
        }
        mvpPresenter?.loadData(videoLink)
    }

    override fun createPresenter() = VideoPlayPresenter()

    override fun createView() = this

    override fun onLoadData(list: List<MultiVideoDetail>) {
        val arrayList = arrayListOf<MultiVideoDetail>().apply { addAll(list) }
        adapter.setNewData(arrayList)
    }

    override fun onLoadVideoUrl(videoUrl: String) {
        iv_cover.setGone()
        if (fl_player_container.visibility != View.VISIBLE) {
            fl_player_container.setVisible()
        }

        gsyVideoOption
                .setUrl(videoUrl)
                .setVideoAllCallBack(object : GSYSampleCallBack() {

                    override fun onPrepared(url: String?, vararg objects: Any) {
                        Debuger.printfError("***** onPrepared **** " + objects[0])
                        Debuger.printfError("***** onPrepared **** " + objects[1])
                        super.onPrepared(url, *objects)
                        //开始播放了才能旋转和全屏
                        orientationHelper.isEnable = true
                        isPlay = true
//                        root.removeView(fab)
                    }

                    override fun onEnterFullscreen(url: String?, vararg objects: Any) {
                        super.onEnterFullscreen(url, *objects)
                        Debuger.printfError("***** onEnterFullscreen **** " + objects[0])//title
                        Debuger.printfError("***** onEnterFullscreen **** " + objects[1])//当前全屏player
                    }

                    override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                        super.onQuitFullscreen(url, *objects)
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[0])//title
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[1])//当前非全屏player
                        orientationHelper.backToProtVideo()
                    }


                })
                .setLockClickListener { _, lock ->
                    //配合下方的onConfigurationChanged
                    orientationHelper.isEnable = !lock
                }
                .setGSYVideoProgressListener { progress, secProgress, currentPosition, duration -> Debuger.printfLog("----", " progress $progress secProgress $secProgress currentPosition $currentPosition duration $duration") }
                .build(detail_player)

        appbar.setExpanded(true, true)
        detail_player.tempPosition = 0L
        detail_player.startPlayLogic()

    }

}